package com.bookRecommend.service.impl;

import com.bookRecommend.commons.MD5Utils;
import com.bookRecommend.mapper.IUserMapper;
import com.bookRecommend.model.User;
import com.bookRecommend.service.IUserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;

@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    IUserMapper mapper;

    @Override
    public List<User> findAllUsers() {
        return mapper.selectAllUsers();
    }

    @Override
    public List<User> findUser(String username) {
        if (username == null || ObjectUtils.isEmpty(username)) {
            return null;
        }
        User user = new User();
        user.setUsername(username);
        return mapper.selectByUser(user);
    }

    @Override
    public User findUserByUsernameAndPassword(String username, String password) {
        if(username == null || username.isEmpty()){
            return null;
        }
        User user = new User();
        user.setUsername(username);
        user.setPassword(MD5Utils.encode(password));
        return mapper.selectByUserNameAnaPassword(user);
    }

    @Override
    public int addUser(String userName, String password, String email) {
        if (userName == null || userName.length() == 0 || password == null || password.length() == 0 || email == null || email.length() == 0) {
            return 0;
        }
        User user = new User();
        user.setUsername(userName);
        user.setPassword(MD5Utils.encode(password));
        user.setEmail(email);
        return mapper.insertUser(user);
    }

    @Override
    public int updatePassword(String password, Integer id) {
        if (password == null || password.length() == 0 || id == null) {
            return 0;
        }
        User user = new User();
        user.setPassword(MD5Utils.encode(password));
        user.setId(id);
        return mapper.updateUser(user);
    }


    @Override
    public PageInfo<User> findPage(Integer n, Integer size, String username) {
        if (n == null ) {
            n = 1;
        }
        if (size == null) {
            size = 5;
        }
        PageHelper.startPage(n, size);
        User user = new User();
        if (username != null) {
            user.setUsername(username);
        }
        return new PageInfo<>(mapper.selectByUser(user));
    }

    @Override
    public int removeById(Integer id) {
        return mapper.deleteById(id);
    }


}
